package cn.anecansaitin.firecrafting.common.net.pack;

import cn.anecansaitin.firecrafting.common.block.entity.FireInterfaceEntity;
import net.minecraft.core.BlockPos;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraftforge.network.NetworkEvent;

import java.util.Objects;
import java.util.function.Supplier;

public record ScreenButtonPressedToBlock(int button, BlockPos pos) {

    public static void encode(ScreenButtonPressedToBlock msg, FriendlyByteBuf buffer) {
        buffer.writeInt(msg.button);
        buffer.writeBlockPos(msg.pos);
    }

    public static ScreenButtonPressedToBlock decode(FriendlyByteBuf buffer) {
        return new ScreenButtonPressedToBlock(buffer.readInt(), buffer.readBlockPos());
    }

    public static void handle(ScreenButtonPressedToBlock packet, Supplier<NetworkEvent.Context> ctx) {
        NetworkEvent.Context context = ctx.get();
        context.enqueueWork(() -> {
            Level world = Objects.requireNonNull(context.getSender()).level;
            BlockEntity entity = world.getBlockEntity(packet.pos);
            if (entity instanceof FireInterfaceEntity) {
                ((FireInterfaceEntity) entity).switchFilterMode();
            }
        });
        context.setPacketHandled(true);
    }
}
